<template>
	<div>
		<van-field
			:required="required"
			readonly
			:clickable="!disabled"
			:clearable="clearable"
			name="calendar"
			:rules="rules"
			:value="value"
			:label="label"
			placeholder="请选择"
			@click="showPop"
		/>
		<van-calendar
			ref="calendar"
			:default-date="defaultDate"
			:min-date="minDate"
			:max-date="maxDate"
			:type="type"
			v-model="showPicker"
			@confirm="onConfirm"
		>
			<template #footer>
				<div class="footer-box">
					<van-button block round @click="reset">重置</van-button>
					<van-button block round type="primary" @click="sure">确认</van-button>
				</div>
			</template>
		</van-calendar>
	</div>
</template>

<script>
import dayjs from 'dayjs'
import { Calendar } from 'vant';
export default {
	name: 'calendar',
	components: {
		'van-calendar':Calendar
	},
	props: {
		rules: {
			type: Array,
			default() {
				return [{ required: true }]
			}
		},
		required: {
			type: Boolean,
			default: true
		},
		label: {
			type: String,
			default: ''
		},
		value: {
			type: String,
			default: ''
		},
		disabled: {
			type: Boolean,
			default: false
		},
		type: {
			type: String,
			default: 'single' // single单个日期 multiple多个日期 range日期区间
		},
		clearable: {
			type: Boolean,
			default: true
		},
		minDate: {
			type: Date,
			require: false
		},
		maxDate: {
			type: Date,
			require: false
		},
		defaultDate: {
			require: false,
			default: null
		}
	},
	data() {
		return {
			isReset:false,
			showPicker: false
		}
	},
	computed: {
		selectDate() {
			return this.value ? new Date(this.value) : new Date(dayjs())
		}
	},
	methods: {
		reset(){
			this.$refs.calendar.reset()
			this.isReset = true
			this.sure()
		},
		showPop() {
			if (this.disabled) {
				return
			}
			this.showPicker = true
		},
		sure(){
			this.$refs.calendar.onConfirm()
			console.log('this.$refs.calendar',this.$refs.calendar);
		},
		onConfirm(val) {
			let value = ''
			if (this.type == 'range') {
				value =
					dayjs(val[0]).format('YYYY-MM-DD') + '~' + dayjs(val[1]).format('YYYY-MM-DD')
			} else if (this.type == 'multiple') {
				for (let i = 0; i < val.length; i++) {
					value += dayjs(val[i]).format('YYYY-MM-DD') + (i != val.length - 1 ? '/' : '')
				}
			} else {
				value = dayjs(val).format('YYYY-MM-DD')
			}
			if(this.isReset){
				value = ''
			}
			this.$emit('update:value', value)
			this.showPicker = false
		}
	}
}
</script>

<style scoped lang="less">
.footer-box {
	display: flex;
    align-items: center;
	.van-button {
		margin: 20px 0;
		&:nth-child(1){
			margin-right: 10px;
			height: 70px;
		}
		&:nth-child(2){
			margin-left: 10px;
			height: 70px;
		}
	}
}
</style>
